package ldk.apps.adbconnections

import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import ldk.apps.adbconnections.handlers.ActionParser

/**
 * 主服务区
 * Created by ldkxingzhe@163.com on 2018/2/2.
 */
class MainService: Service() {
    private val TAG = "MainService"
    private val notificationId = 318

    private val binder = LocalBinder()
    private lateinit var notificationManager: NotificationManager
    private lateinit var server: MainServer
    private lateinit var actionParser: ActionParser

    inner class LocalBinder: Binder(){
        val service = this@MainService
    }

    override fun onBind(intent: Intent?): IBinder {
        return binder
    }

    override fun onCreate() {
        super.onCreate()
        notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        Log.v(TAG, "onCreate")
        showNotification()
        actionParser = ActionParser()
        server = MainServer()
        server.handleLog = {
            Log.d(TAG, it)
        }
        server.handleOnAccept = {
            Log.d(TAG, "有人连接成功")
        }
        server.shouldAccept = { true }
        server.handleOnAction = {
            action: Int, content: ByteArray? ->
            actionParser.handle(server, action.toShort(), content)
        }
    }

    private fun showNotification(){
        val activity = PendingIntent.getActivity(this, 0,
                Intent(this, MainActivity::class.java),
                PendingIntent.FLAG_UPDATE_CURRENT)
        val notification = Notification.Builder(this)
                .setContentTitle("AdbConnection is running")
                .setContentText("adb 服务器正在运行")
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentIntent(activity)
                .build()
        notification.flags = Notification.FLAG_FOREGROUND_SERVICE
        startForeground(notificationId, notification)
    }

    fun stopService(){
        Log.v(TAG, "stopService")
        stopForeground(true)
        stopSelf()
    }

    override fun onDestroy() {
        super.onDestroy()
        server.closeServer()
        Log.v(TAG, "onDestroy")
    }
}